// 采购确认
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, Table, Switch, message, Pagination, Input, Checkbox, Icon } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import './style/index.less'
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
var standingNumber = 0; //确认单序列号

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};
const formItemSwitch = {    // label 和input宽度
    labelCol: { span: 15 },
    wrapperCol: { span: 8 },
};
const PurchaseConfirmation = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                data: [],
                queryCondition: {},
                SelectData: {},
                detailsId: '',//确认单ID
                WaListData: [], //确认单数据
                vendorDesc: [], //供应商数据
                pageSize: 20,
                page: 1,
                pageSize2: 20,
                page2: 1,
                total: 0,
                show: false,
                vouchingId: [],
                selectedRowKeys: [],
                id: '30',
                stateData: [],  //状态下拉框
                stateBoolean: false,
                modalColumns: [],
                detailWidthTotal: '',
                columns: [],
                columnsWidth: '',
                ChineseEnglishSize: [],
            };

            // 供应商的数据表头
            this.columns = [
                {
                    key: 1,
                    title: '供应商',
                    dataIndex: 'vendorDesc',
                    align: "center",
                    width: '100%'
                }
            ];
            // 确认单详细表头
            this.modalColumns = [
                {
                    key: 1,
                    title: '确认单号',
                    dataIndex: 'stkPayNO',
                    align: "center",
                    width: '16%'
                },
                {
                    key: 2,
                    title: '状态',
                    dataIndex: 'stateDesc',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 3,
                    title: '进价金额',
                    dataIndex: 'rpAmt',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 4,
                    title: '将付金额',
                    dataIndex: 'willPay',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 5,
                    title: '制单日期',
                    dataIndex: 'createDate',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 6,
                    title: '采购确认',
                    dataIndex: 'purCheckUser',
                    align: "center",
                    width: '14%'
                },
                {
                    key: 7,
                    title: '财务确认',
                    dataIndex: 'finaCheckUser',
                    align: "center",
                    width: '14%'
                }
            ]
        }

        componentDidMount() {
            // 初始化数据
            this.getTacitlyApproveData();
            this.getDetailTableColumns();
            //this.getColumnsLeft();
            this.getvendorList();
            let dom = document.querySelectorAll('.waListHeight  .ant-table-body');
            dom[0].style.height = store.getState().tableHeight.y - 55 + 'px';
            let detailsHeight = document.querySelectorAll('.detailsHeight  .ant-table-body');
            detailsHeight[0].style.height = store.getState().tableHeight.y - 55 + 'px';
        }

        // 获取明系列表头数据
        getDetailTableColumns = () => {
            let { userInfo } = this.state;
            let data = {
                params: [{
                    reactCode: ['PurchaseConfirmation'],
                    compontName: 'PurchaseConfirmationList',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return {
                                ...item,
                                key: index + 1,
                                title: <div onDoubleClick={() => { this.columnRef.onOpenModel(); }}>{userInfo.language == 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ modalColumns: filterArr, detailWidthTotal: res.totalWidth, ChineseEnglishSize: userInfo.language == 'EN' ? res.result.language.EN : res.result.language.CN })
                    }
                }
            });
        };

        //页面中英文翻译
        getColumnsLeft = () => {
            let { userInfo } = this.state;
            let data = {
                params: [{
                    compontName: 'ProcurementConLeftColum',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                            return {
                                ...item,
                                key: index + 1,
                                title: <div>{userInfo.language == 'EN' ? item.enDescripts : item.title}</div>
                            }
                        }) : '';
                        let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                        this.setState({ columns: filterArr, columnsWidth: res.totalWidth })
                    }
                }
            })
        };

        // 获取界面默认值
        getTacitlyApproveData() {
            let data = {
                params: []
            };
            // 获取起止时间和是否审核
            // $http.post('urlS', this, {
            //     code: "02020059",
            //     data: data,
            //     success: function (res) {
            //         if (+res.errorCode === 0) {
            //             this.setState({queryCondition: res.result[0]})
            //         }
            //     }
            // });
            // 获取下拉数据
            $http.post('urlS', this, {
                code: "02020143",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let arr = ['30', '40'];
                        let newArr = []
                        for (var i = 0; i < arr.length; i++) {
                            newArr.push(res.state.find(item => item.id == arr[i]))
                        }
                        this.setState({ SelectData: res, stateData: newArr })
                    }
                }
            })
        }

        // 获取待审核数据
        getVouchingList = (num) => {
            let { ChineseEnglishSize } = this.state;
            this.setState({ loading: true })
            let state = this.props.form.getFieldValue('state');
            let EndData = this.props.form.getFieldValue('EndData');
            let StartDate = this.props.form.getFieldValue('StartDate');
            let data = {
                params: [{
                    begin: Moment(StartDate).format('YYYY-MM-DD'),
                    end: Moment(EndData).format('YYYY-MM-DD'),
                    vendorID: this.state.detailsId ? this.state.detailsId : undefined,
                    stateID: state ? state : undefined
                }],
                pagination: [
                    {
                        pageSize: this.state.pageSize2,
                        currentPage: this.state.page2,
                        sort: "ID",
                        dir: "asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020146",
                data: data,
                success: function (res) {
                    if (res.rows.length > 0) {
                        for (var i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                            res.rows[i].purCheckUser = res.rows[i].purCheckUserName + res.rows[i].purCheckDate;
                            res.rows[i].finaCheckUser = res.rows[i].finaCheckUserName + res.rows[i].finaCheckDate;
                        }
                        this.setState({ WaListData: res.rows, total: res.total, selectedRowKeys: [], loading: false });
                        standingNumber = 0;
                    } else {
                        this.setState({ WaListData: [], selectedRowKeys: [] });
                        if (num !== '1') {
                            message.error(ChineseEnglishSize.PurchaseConfirmationnoData ? ChineseEnglishSize.PurchaseConfirmationnoData.descripts : "没数据")
                        }
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

        // 获取供应商列表数据
        getvendorList = (num) => {
            let { ChineseEnglishSize } = this.state;
            this.setState({ loading: true })
            let state = this.props.form.getFieldValue('state');
            let EndData = this.props.form.getFieldValue('EndData');
            let StartDate = this.props.form.getFieldValue('StartDate');
            let data = {
                params: [{
                    begin: Moment(StartDate).format('YYYY-MM-DD'),
                    end: Moment(EndData).format('YYYY-MM-DD'),
                    stateID: state ? state : undefined
                }],
                pagination: [
                    {
                        sort: "ID",
                        dir: "asc",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020337",
                data: data,
                success: function (res) {
                    if (res.rows.length > 0) {
                        this.setState({ vendorDesc: res.rows, loading: false });
                        standingNumber = 0;
                        // this.getWarehouseEntryDetails(res.rows[0].stkLocID)
                        this.getVouchingList(res.rows[0].stkLocID)
                    } else {
                        this.setState({ vendorDesc: [], });
                        if (num !== '1') {
                            message.error(ChineseEnglishSize.PaymentManagementnoData ? ChineseEnglishSize.PaymentManagementnoData.descripts : "没数据")
                        }
                    }
                },
                error: function (err) {
                    message.error(err.errorMessage)
                }
            });
        };

        // 确认
        dataVouching = () => {
            let { ChineseEnglishSize } = this.state;
            let { vouchingId } = this.state;
            if (vouchingId.length > 0) {
                let arr = vouchingId && vouchingId.map(item => {
                    return {
                        stkPayID: item.stkPayID
                    }
                });
                let data = {
                    params: arr
                };
                $http.post('urlS', this, {
                    code: "02020149",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(res.errorMessage);
                            this.setState({ vouchingId: [] })
                            this.getVouchingList('1');
                        }
                    }
                })
            } else {
                message.error(ChineseEnglishSize.PurchaseConfirmationselectConfiData ? ChineseEnglishSize.PurchaseConfirmationselectConfiData.descripts : '请选择确认数据')
            }

        };

        //点击行，渲染当前行样式
        setRowClassName = (record) => {
            standingNumber = standingNumber + 1;
            if (record) {
                if (this.state.detailsId == record.id) return 'clickRowStyle';
                // else if (standingNumber == 1) return 'clickRowStyle';
                else return '';
                // return this.state.detailsId == record.inOperateID ? 'clickRowStyle ': '';
            } else {
                return '';
            }
        };



        // 页码改变的回调，参数是改变后的页码及每页条数
        // onChange = (page, pageSize) => {
        //     this.setState({page: page, pageSize: pageSize}, () => {
        //         // 重新调用查询方法
        //         this.getVouchingList();
        //     });
        // };
        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }
        // onShowSizeChange = (current, size) => {
        //     this.setState({page: current, pageSize: size}, () => {
        //         // 重新调用查询方法
        //         this.onChange(current,size);
        //     })
        // };

        // 页码改变的回调，参数是改变后的页码及每页条数 确认单详情
        onChange2 = (page, pageSize) => {
            this.setState({ page2: page, pageSize2: pageSize }, () => {
                // 重新调用查询方法
                this.getVouchingList();
            });
        };

        onShowSizeChange2 = (current, size) => {
            this.setState({ page2: current, pageSize2: size }, () => {
                // 重新调用查询方法
                this.onChange2(current, size);
            })
        };

        // 收起明细录入
        packUpHandle = () => {
            this.setState({ show: !this.state.show, span: 24 })
        };

        setPaymentClassName = (record) => {
            // 选中行class名
            return (("^" + this.state.selectedRowKeys.join("^") + "^").indexOf("^" + record.key + "^") > -1) ? 'clickRowStyle' : '';
        };

        onClickRow = (record) => {
            return {
                onClick: () => {
                    let { selectedRowKeys, vouchingId } = this.state;
                    let findFlag = false;
                    let start = 0;
                    if (selectedRowKeys) {
                        selectedRowKeys.find(function (value, key) {
                            if (value === record.key) {
                                //遍历找到选中的数据，并记录下选中数据在数组中的key
                                findFlag = true;
                                start = key;
                            }
                        })
                    }
                    if (findFlag) {
                        //再次点击移除选中
                        selectedRowKeys.splice(start, 1);
                        vouchingId.splice(start, 1);
                    } else {
                        //将点击的行添加到选中
                        selectedRowKeys.push(record.key);
                        vouchingId.push(record);
                    }
                    if (this.state.rowId === "") {
                        this.setState({
                            rowId: record.key,
                            selectedRowKeys,
                            vouchingId
                        });
                    } else {
                        if (this.state.rowId !== record.key) {
                            this.setState({
                                rowId: record.key,
                                selectedRowKeys,
                                vouchingId
                            });
                        } else {
                            this.setState({
                                rowId: "",
                                selectedRowKeys,
                                vouchingId
                            });
                        }
                    }
                    let result = this.state.vouchingId.some(function (item) {
                        if (item.stateID == '40') {
                            return true;
                        }
                    });
                    this.setState({ stateBoolean: result })
                }
            }
        }

        //组件权限编辑器
        onColumnRef = (ref) => {
            this.columnRef = ref;
        };

        render() {
            const { getFieldDecorator } = this.props.form;
            let userInfo = this.state.userInfo ? this.state.userInfo : {};
            let { ChineseEnglishSize, columns, modalColumns } = this.state;
            //确认部门下拉列表
            let loc = [];
            let state = [];
            this.state.SelectData.loc && this.state.SelectData.loc.map((item, i) => {
                loc.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });
            this.state.stateData.length > 0 && this.state.stateData.map((item, i) => {
                item&&state.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            const rowSelection = {
                selectedRowKeys: this.state.selectedRowKeys,
                selectedRows: this.state.vouchingId,
                onChange: (selectedRowKeys, selectedRows) => {
                    let rowId = "";
                    if (selectedRowKeys.length !== 0) {
                        rowId = selectedRowKeys[selectedRowKeys.length - 1];
                    }
                    this.setState({ selectedRowKeys: selectedRowKeys, vouchingId: selectedRows, rowId: rowId })
                }
            };
            return (
                <div className="paymentVouching">
                    <Row>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.PurchaseConfirmationpurchaseCon ? ChineseEnglishSize.PurchaseConfirmationpurchaseCon.descripts : '采购确认'}</div>}
                        >
                            <Col span={13}>
                                <Form>
                                    <Row >
                                        {/*<Col span={6}>*/}
                                        {/*<FormItem {...formItemLayout} label="科室">*/}
                                        {/*{getFieldDecorator('locDr',{*/}
                                        {/*initialValue: this.state.userInfo.locID ? this.state.userInfo.locID : undefined,*/}
                                        {/*rules:[{ required : true, message: '科室不能为空'}]*/}
                                        {/*})(*/}
                                        {/*<Select allowClear={true}>*/}
                                        {/*{loc}*/}
                                        {/*</Select>*/}
                                        {/*) }*/}
                                        {/*</FormItem>*/}
                                        {/*</Col>*/}
                                        <Col span={6}>
                                            <FormItem {...formItemLayout} label={ChineseEnglishSize.PurchaseConfirmationstate ? ChineseEnglishSize.PurchaseConfirmationstate.descripts : '状态'}>
                                                {getFieldDecorator('state', {
                                                    initialValue: this.state.id ? this.state.id : undefined,
                                                    rules: [{ required: false, message: '状态不能为空' }]
                                                })(
                                                    <Select className="abcd">
                                                        {state}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={4} className="queryTime" style={{ marginLeft: '30px' }}>
                                            <FormItem>
                                                {getFieldDecorator('StartDate', {
                                                    initialValue: this.state.queryCondition.startDate ? Moment(this.state.queryCondition.startDate, 'YYYY-MM-DD') : Moment(),
                                                    rules: [{ required: ChineseEnglishSize.PurchaseConfirmationStartData ? ChineseEnglishSize.PurchaseConfirmationStartData.required == 'Y' ? true : false : false, message: ChineseEnglishSize.PurchaseConfirmationStartData ? ChineseEnglishSize.PurchaseConfirmationStartData.message : '起初日期不能为空' }]
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={1} style={{ textAlign: 'center', lineHeight: '37px' }}>
                                            <span>到</span>
                                        </Col>
                                        <Col span={4} className="queryTime">
                                            <FormItem>
                                                {getFieldDecorator('EndData', {
                                                    initialValue: this.state.queryCondition.endDate ? Moment(this.state.queryCondition.endDate, 'YYYY-MM-DD') : Moment(),
                                                    rules: [{ required: ChineseEnglishSize.PurchaseConfirmationdeadline ? ChineseEnglishSize.PurchaseConfirmationdeadline.required == 'Y' ? true : false : false, message: ChineseEnglishSize.PurchaseConfirmationdeadline ? ChineseEnglishSize.PurchaseConfirmationdeadline.message : '截至日期不能为空' }]
                                                })(
                                                    <DatePicker style={{ width: '100%' }} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={4} style={{ marginLeft: '30px' }}>
                                            <Row style={{ marginTop: '4px' }} className="buttonLeft">
                                                <Button onClick={this.getvendorList}>{ChineseEnglishSize.PurchaseConfirmationsearch ? ChineseEnglishSize.PurchaseConfirmationsearch.descripts : '查询'}</Button>
                                            </Row>
                                        </Col>
                                    </Row>
                                </Form>
                            </Col>
                            <Col span={10} style={{ textAlign: 'right' }}>
                                <Row style={{ marginTop: '4px' }} className="buttonRight">
                                    <Button disabled={this.state.selectedRowKeys.length > 0 && this.props.form.getFieldValue('state') !== '40' ? false : true} onClick={this.dataVouching}>{ChineseEnglishSize.PurchaseConfirmationpurchaseCon ? ChineseEnglishSize.PurchaseConfirmationpurchaseCon.descripts : '采购确认'}</Button>
                                </Row>
                            </Col>
                        </Card>
                    </Row>
                    <Row>
                        <Col span={6} style={{ display: this.state.show ? 'none' : '' }} className={!this.state.show ? "animate-wrap active down-in" : "animate-wrap"}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.PurchaseConfirmationsupplier ? ChineseEnglishSize.PurchaseConfirmationsupplier.descripts : '供应商'}</div>}
                            >
                                <div className="drugList ">
                                    <Table
                                        columns={columns.length > 0 ? columns : this.columns}
                                        dataSource={this.state.vendorDesc}
                                        pagination={false}
                                        bordered
                                        scroll={{ y: store.getState().tableHeight.y - 52 }}
                                        rowClassName={this.setRowClassName}
                                        rowKey={record => record.key}
                                        className='waListHeight'
                                        onRow={(record) => {
                                            return {
                                                onClick: () => {
                                                    standingNumber = 9999;
                                                    if (this.state.detailsId === '') {
                                                        // 保存行数据以及ID
                                                        this.setState({ detailsId: record.id, page2: 1 }, () => {
                                                            this.getVouchingList()
                                                        });

                                                    } else {
                                                        if (this.state.detailsId !== record.id) {
                                                            this.setState({ detailsId: record.id, page2: 1 }, () => {
                                                                this.getVouchingList()
                                                            });
                                                        } else {
                                                            this.setState({ detailsId: '', page2: 1 });
                                                        }
                                                    }
                                                },

                                            };
                                        }}
                                    />
                                    {/*<Pagination*/}
                                    {/*showTotal={() => this.showTotal(this.state.total)}*/}
                                    {/*size="small"*/}
                                    {/*showQuickJumper*/}
                                    {/*showSizeChanger*/}
                                    {/*defaultCurrent={1}*/}
                                    {/*total={this.state.total ? this.state.total : 0}*/}
                                    {/*onChange={this.onChange}*/}
                                    {/*onShowSizeChange={this.onShowSizeChange}*/}
                                    {/*style={{textAlign: "right", marginTop: '13px'}}*/}
                                    {/*/>*/}
                                </div>
                            </Card>
                        </Col>
                        <Col span={this.state.show ? 24 : 18}>
                            <Card
                                size="small"
                                title={<span><Icon onClick={this.packUpHandle} type={this.state.show ? 'double-right' : 'double-left'} />{ChineseEnglishSize.PurchaseConfirmationpurchaseConForm ? ChineseEnglishSize.PurchaseConfirmationpurchaseConForm.descripts : '采购确认单'}</span>}
                                extra={<span style={{ color: '#666' }} className='span' onClick={() => { this.columnRef.onOpenModel(); }}><Icon type="setting" title={ChineseEnglishSize.PurchaseConfirmationcolumnSettings ? ChineseEnglishSize.PurchaseConfirmationcolumnSettings.descripts : '列权限设置'} /></span>}
                            >
                                <div>
                                    <Table
                                        rowSelection={rowSelection}
                                        columns={modalColumns.length > 0 ? modalColumns : this.modalColumns}
                                        dataSource={this.state.WaListData}
                                        pagination={false}
                                        bordered
                                        scroll={{ x: this.state.detailWidthTotal ? this.state.detailWidthTotal : 1600, y: store.getState().tableHeight.y + 2 }}
                                        rowKey={record => record.key}
                                        className='detailsHeight'
                                        onRow={this.onClickRow}
                                        rowClassName={this.setPaymentClassName}
                                    />
                                    <CommonPagination size='small' current={this.state.page2} total={this.state.total} search='search'
                                        onShowSizeChange={this.onShowSizeChange2.bind(this)} complete={true} dataSource={this.state.WaListData}
                                        loading={this.state.loading} onChange={this.onChange2.bind(this)} pageSize={true} />
                                </div>
                            </Card>
                        </Col>
                    </Row>
                    {/*//显示表头修改弹窗*/}
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='PurchaseConfirmationList'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns}
                    />
                </div>
            )
        }
    }
);
export default PurchaseConfirmation;